<!-- 申诉管理页面-->
<!DOCTYPE html>
<html lang="en">
<head>
    <script src="${request.contextPath}/static/js/jquery-3.4.1.min.js"></script>
    <script src="${request.contextPath}/static/layui/layui.js"></script>
    <script src="${request.contextPath}/static/layui/layui_exts/excel.js"></script>
    <link rel="stylesheet" href="${request.contextPath}/static/layui/css/layui.css">
    <style>
        #import{
            opacity: 0;
            z-index: 9999;
            position: absolute;
            top: 5px;
        }
        #importFake{
            position: absolute;
        }

        /*.layui-table-cell{*/
        /*    text-align:center;*/
        /*    height: auto;*/
        /*    white-space: normal;*/
        /*}*/
        .layui-table img{
            max-width:300px;
        }
        .layui-form{
          margin-top: 10px;
        }
        .layui-table-tool{
          dispaly: none
        }
        #test10{
          width: 290px;
        }
        .layui-input-inline{
          width: auto !important;
          min-width: 190px !important;
        }
        .layui-table-cell, .layui-table-tool-panel li{
          overflow: inherit
        }
        td .layui-input, .layui-select, .layui-textarea{
          height: 28px;
        }

    </style>
</head>

<body>
<div class="layui-form">
    <div class="layui-form-item">
        <div class="layui-inline">
            <div class="layui-input-inline">
                <input type="text" class="layui-input" id="test10" placeholder="请选择发送时间" readonly="readonly">
            </div>
            <div class="layui-input-inline">
                <select name="type" lay-verify="" id="type" lay-filter="type">
                    <option value="">请选择处理状态</option>
                    <option value="0">未处理</option>
                    <option value="1">处理中</option>
                    <option value="2">已处理</option>
                </select>
            </div>
            <div class="layui-input-inline">
                <button class="layui-btn" id="withExport">查询</button>
            </div>
            <div class="layui-input-inline">
                <button class="layui-btn" id="sendMsg">发送短信</button>
            </div>
            <#--  <div class="layui-input-inline">
                <button type="button" class="layui-btn" id="test3"><i class="layui-icon"></i>导入Excel文件</button>
            </div>  -->
            <div class="layui-input-inline">
                <button type="button" class="layui-btn layui-btn-danger" id="export"><i class="layui-icon">&#xe67d;</i>导出Excel文件</button>
            </div>
            <div class="layui-input-inline">
                <button type="button" class="layui-btn" id="importFake"><i class="layui-icon"></i>导入Excel文件</button>
                <input type="file" id="import"></input>
            </div>



        </div>
    </div>
</div>
<table class="layui-table" id="post-table" lay-filter="post-table"></table>

<script type="text/html" id="rank">
    {{d.LAY_TABLE_INDEX+1}}
</script>
<script type="text/html" id="state">
    {{d.state = d.state == 0 ? "未处理" : (d.state == 1 ? "处理中" : "已处理")}}
</script>
<script type="text/html" id="img">
    <div><img  src="${request.contextPath}{{ d.img }}"></div>
<#--    <div><img  src="${request.contextPath}/static/images/logos/unionpay-logo.png"></div>-->
</script>
<script type="text/html" id="feedback">
    {{# if(d.msgTemplate === "0"){ }}
    {{ "未配置" }}
    {{# }else if(d.msgTemplate === "1"){ }}
    {{ "已受理" }}
    {{# }else if(d.msgTemplate === "2"){ }}
    {{ "申诉驳回" }}
    {{#  } else { }}
    {{ "数据异常" }}
    {{#  } }}
</script>
<script type="text/html" id="msgStatus">
    {{d.msgStatus = d.msgStatus == 0 ? "未发送" : (d.msgStatus == 1 ? "已发送" : "发送失败")}}
</script>

<script type="text/html" id="barTpl">
    <a class="layui-btn layui-btn-xs" lay-event="edit">保存</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script>
    var layerCallback;
    var json;
    var returnData;
    var url = "${request.contextPath}/findByParams";
    window.onload=function(){
        $.ajax({
            url: url,
            success: function(res){
                returnData = res.data;
            }
        });
        // 监听上传文件的事件
        $('#import').change(function(e) {
            let files = e.target.files;
            if(files != null){
                var name = files[0].name.split(".")[1];
            }else{
                return;
            }
            if(name == "xlsx" || name == "xls"){
                uploadExcel(files);
            }else{
                layer.alert("请上传excel文件！");
            }
        });
    };
    layui.use(['table','upload','laydate'], function(){
        let table = layui.table;
        let $ = layui.jquery;
        let upload = layui.upload;
        let laydate = layui.laydate;
        table.render({
            type:'numbers',
            elem: '#post-table',
            url:'${request.contextPath}/complain',
            // toolbar: '#toolbar',
            defaultToolbar: [],
            parseData: function (res) {
                return {
                    "code": 0,
                    "msg": res.msg,
                    "count": res.size,
                    data: res.data
                }
            }
            ,cols: [[
                {field: 'id', title: 'ID', width: 50},
                {field:'phone', width:200, title: '申诉人手机号'},
                // {field:'img', width:200, title: '截图' ,templet: '#img'},
                {field:'content', width:400, title:'申诉内容'},
                {field:'startTime', width:180, title: '申诉时间'},
                {field:'state', width:150, title: '申诉状态', templet: function (row) {
                        var stateSet = ['未处理','处理中','已处理'];
                        var stateHtml = '';
                        var isSelected = '';
                        for(var stateIndex=0; stateIndex<stateSet.length; stateIndex++){
                          if(stateIndex == row.state){
                            isSelected = 'selected'
                          }else{
                            isSelected = ''
                          }
                          stateHtml += '<option value='+stateIndex+' '+isSelected+'>'+stateSet[stateIndex]+'</option>'
                        }
                        return '<select name="state" lay-verify="" id="state" lay-filter="state">'
                          + stateHtml
                          +'</select>'
                      }
                },
                {field:'msgTemplate', width:150, title:'短信模板', templet: function (row) {
                        var msgTemplateSet = ['未配置','已受理','申诉驳回'];
                        var msgTemplateHtml = '';
                        var isSelected = '';
                        for(var msgTemplateIndex=0; msgTemplateIndex < msgTemplateSet.length; msgTemplateIndex++){
                          if(msgTemplateIndex == row.msgTemplate){
                            isSelected = 'selected'
                          }else{
                            isSelected = ''
                          }
                          msgTemplateHtml += '<option value='+msgTemplateIndex+' '+isSelected+'>'+msgTemplateSet[msgTemplateIndex]+'</option>'
                        }
                        return '<select name="msgTemplate" lay-verify="" id="msgTemplate" lay-filter="msgTemplate">'
                          + msgTemplateHtml
                          +'</select>'
                      }
                },
                {field:'msgStatus', width:150, title: '短信状态', templet: '#msgStatus',edit: true},
                {field:'createdTime', width:180, title: '创建时间', sort: true},
                {field:'updatedTime', width:180, title: '更新时间'},

                {fixed: 'right', width:150, align:'center', toolbar: '#barTpl'}
            ]]
            ,page: true
        });
        //监听工具条(右侧)
        table.on('tool(post-table)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            if(layEvent === 'edit'){ //编辑
                //var state = (data.state = data.state == "未处理" ? 0 : (data.state == "处理中" ? 1 : 2));
                console.log(data);
                var state = $("#state").val();
                var msgTemplate = $("#msgTemplate").val();
                // var msgTemplate = 0;
                // if(data.msgTemplate == "已受理"){
                //     msgTemplate = 1;
                // }else if(data.msgTemplate == "申诉驳回"){
                //     msgTemplate = 2;
                // }

                // 发送更新请求
                $.ajax({
                    url: '${request.contextPath}/complain',
                    method: 'put',
                    data: JSON.stringify({
                        id: data.id,
                        state: state,
                        msgTemplate:msgTemplate,
                        result: data.result,
                        remark: data.remark
                    }),
                    contentType: "application/json",
                    success: function (res) {
                        if (res.code == 200) {
                            layer.msg('修改成功', {icon: 1});
                            table.reload("post-table",{
                                url: '${request.contextPath}/complain',
                                page: {
                                    curr: 1
                                }
                            });
                            // obj.update({
                            //     result: data.result,
                            //     remark: data.remark
                            // });
                        } else {
                            layer.msg('修改失败', {icon: 2});
                        }
                    }
                });
            } else if (layEvent == 'del') {
                layer.confirm('删除申诉信息?', {skin: 'layui-layer-molv',offset:'c', icon:'0'},function(index){
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    layer.close(index);
                    //向服务端发送删除指令
                    $.ajax({
                        url: '${request.contextPath}/complain/' + data.id,
                        type: 'delete',
                        success: function (res) {
                            if (res.code == 200) {
                                layer.msg('删除成功', {icon: 1, skin: 'layui-layer-molv', offset:'c'});
                                table.reload("post-table",{
                                    url: '${request.contextPath}/complain',
                                    page: {
                                        curr: 1
                                    }
                                });
                            } else {
                                layer.msg('删除失败', {icon: 2, skin: 'layui-layer-molv', offset:'c'});
                            }
                        }
                    })
                });
            }
        });
        //指定允许上传的文件类型
        upload.render({
            elem: '#test3'
            ,url: '${request.contextPath}/upload' //改成您自己的上传接口
            ,accept: 'file' //普通文件
            ,exts: 'xls|xlsx'
            ,done: function(res){
            parent.layer.alert(res.data, {icon: 1, skin: 'layui-layer-molv', offset:'c'});
            window.location.reload();
            }
        });
        //日期时间范围
        var ins1 = laydate.render({
            elem: '#test10'
            ,type: 'datetime'
            ,range: true
            ,ready: function(value){
              $(".layui-laydate-footer [lay-type='datetime'].laydate-btns-time").click();
              // 改变结束时间默认值
              $(".laydate-main-list-1 .layui-laydate-content li ol li:last-child").click();
              $(".layui-laydate-footer [lay-type='date'].laydate-btns-time").click();
            }
        });
    });
    var isLock = false;
    // 发送短信
    $("#sendMsg").click(function(res) {
        var str = "将会对所有短信状态是【未发送】和【发送失败】的记录发送短信，是否确认？";
        layer.confirm(str,{
            btn: ["确定","取消"]
        },function(index) {
            if(isLock){
                layer.msg('请等待服务器返回！');
                return;
            }
            isLock = true;
            var api = "${request.contextPath}/sendComplainMsg";
            $.ajax({
                url: api,
                success: function(res){
                    isLock = false;
                    console.log(res);
                    layer.msg('已成功发送短信'+res+"条！");
                    let table = layui.table;
                    table.reload("post-table",{
                        url: '${request.contextPath}/complain',
                        page: {
                            curr: 1
                        }
                    });
                }
            });
        });


    });

    //查询功能
    $("#withExport").click(function(){
        var table = layui.table;
        var type = $("#type").val();
        var time = $("#test10").val();
        var startTime = '';
        var endTime = '';
        var dataList = {};
        if(time != '' && type != ''){//根据时间和申诉状态查询
            startTime = StringToDate(time.substring(0,19));
            endTime = StringToDate(time.substring(22,42));
            dataList = {
                startTime : startTime,
                endTime : endTime,
                state : type
            };
            table.reload("post-table",{
                url: '${request.contextPath}/find',
                where: dataList,
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                done: function(res){
                    this.where={};
                }
            });
            $.ajax({
                url: url,
                data: dataList,
                success: function(res){
                    returnData = res.data;
                }
            });           
        }else if(time == '' && type == ''){//查询所有数据
            table.reload("post-table",{
                url: '${request.contextPath}/complain',
                page: {
                    curr: 1
                },
                done: function(res){
                    this.where={};
                }
            });
            $.ajax({
                url: url,
                success: function(res){
                    returnData = res.data;
                }
            });
        }else if(time != '' && type == ''){//查询指定时间段内所有数据
            startTime = StringToDate(time.substring(0,19));
            endTime = StringToDate(time.substring(22,42));
            dataList = {
                startTime : startTime,
                endTime : endTime
            };
            table.reload("post-table",{
                url: '${request.contextPath}/find',
                where: dataList,
                page: {
                    curr: 1
                },
                done: function(res){
                    this.where={};
                }
            });
            $.ajax({
                url: url,
                data: dataList,
                success: function(res){
                    returnData = res.data;
                }
            });
        }else if(time == '' && type != ''){//根据状态查询所有数据
            dataList = {state : type};
            table.reload('post-table',{
                url: '${request.contextPath}/find',
                where: dataList,
                page: {
                    curr: 1
                },
                done: function(res){
                    this.where={};
                }
            });
            $.ajax({
                url: url,
                data: dataList,
                success: function(res){
                    returnData = res.data;
                }
            });
        }           
    });
    //字符串转日期
    function StringToDate(s) {
        var d = new Date(); 
        d.setYear(parseInt(s.substring(0,4),10)); 
        d.setMonth(parseInt(s.substring(5,7)-1,10)); 
        d.setDate(parseInt(s.substring(8,10),10)); 
        d.setHours(parseInt(s.substring(11,13),10)); 
        d.setMinutes(parseInt(s.substring(14,16),10)); 
        d.setSeconds(parseInt(s.substring(17,19),10));
        return d; 
    }
    //导出功能
    var flag = false;
    $("#export").click(function(){
        if(!flag){
            returnData = LAY_EXCEL.filterExportData(returnData,{
                id: 'id',
                state:function(value, line, data) {
                    return value = value == 0 ? "未处理" : (value == 1 ? "处理中" : "已处理") ;
                },
                phone: 'phone',
                content: 'content',
                startTime: 'startTime',
                result: 'result',
                msgTemplate: 'msgTemplate',
                msgStatus: 'msgStatus'
            });
            returnData.unshift({id: 'ID',phone: '申诉人手机号', content: '申诉内容',startTime: '申诉时间', state: '申诉状态',result: '反馈信息',msgTemplate: '短信模板',msgStatus: '短信状态'});
            flag = !flag;
        }
        if(flag){
            var date = new Date();
            var month = (date.getMonth()+1) > 9 ? (date.getMonth()+1) : '0'+(date.getMonth()+1);
            var day = date.getDate() > 9 ? date.getDate() : '0'+date.getDate();
            var hours = date.getHours() > 9 ? date.getHours() : '0'+date.getHours();
            var min = date.getMinutes() > 9 ? date.getMinutes() : '0'+date.getMinutes();
            var sec = date.getSeconds() > 9 ? date.getSeconds() : '0'+date.getSeconds();
            var name = date.getFullYear()+month+day+"_"+hours+min+sec;
            LAY_EXCEL.exportExcel({
                sheet1: returnData
            }, name+'.xlsx', 'xlsx');
        }
    });
    //导入功能
    function uploadExcel(files) {
        try {
            LAY_EXCEL.importExcel(files, {
            // 读取数据的同时梳理数据
                fields: {
                    'id': 'A'
                    ,'phone': 'B'
                    ,'content': 'C'
                    ,'startTime': 'D'
                    ,'state': 'E'
                    ,'result': 'F'
                    ,'msgTemplate': 'G'
                }
            },function(data){
                    data = LAY_EXCEL.filterImportData(data, {
                    id: 'id'
                    ,state: function(value, line, data) {
                            return value = value == "未处理" ? 0 : (value == "处理中" ? 1 : 2) ;
                        }
                    ,msgTemplate:  'msgTemplate'
                    ,result: 'result'
                    ,remark: 'remark'
                });
                // 如果不需要展示直接上传，可以再次 $.ajax() 将JSON数据通过 JSON.stringify() 处理后传递到后端即可
                $.ajax({
                    url: '${request.contextPath}/uploadExcel'
                    , data:JSON.stringify(data[0])
                    , contentType: "application/json"
                    , type: 'post'
                    , success: function (res) {
                        parent.layer.alert(res.data, {icon: 1, skin: 'layui-layer-molv', offset:'c'});
                        window.location.reload();
                    }
                });
            });           
        }catch(e){
            layer.alert("上传出错");
        }
    }
</script>
</body>
</html>